package com.rrd.hive.udf;

import org.apache.hadoop.hive.ql.exec.UDF;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class ParseTable2UDF extends UDF {
    Pattern pattern = Pattern.compile("(?i)(?:from|join)\\s+([a-z]+\\.?\\s*[a-zA-Z0-9_]+)");

    public List<String> evaluate(String sql) {
        if (sql == null) {
            return null;
        }
        sql = sql.replace("`", "");
        List<String> list = new ArrayList<>();
        Matcher m = pattern.matcher(sql);
        while (m.find()) {
            try {
                list.add(m.group(1));
            } catch (IndexOutOfBoundsException ex) {
                ex.printStackTrace();
            }
        }
        if (list.size() == 0) {
            list.add("");
        }
        return list;
    }

    public static void main(String[] args) {
        String a = "SELECT `mr_business_h5_regincome_d`.`cli_mhuanbi` AS `cli_mhuanbi`,   `mr_business_h5_regincome_d`.`cli_user_cnt_mtd` AS `cli_user_cnt_mtd`,   `mr_business_h5_regincome_d`.`cli_user_cnt_pmtd` AS `cli_user_cnt_pmtd`,   `mr_business_h5_regincome_d`.`cli_uv_rate_mhuanbi` AS `cli_uv_rate_mhuanbi`,   `mr_business_h5_regincome_d`.`cli_uv_rate_mtd` AS `cli_uv_rate_mtd`,   `mr_business_h5_regincome_d`.`cli_uv_rate_pmtd` AS `cli_uv_rate_pmtd`,   CAST (TO_DATE(`mr_business_h5_regincome_d`.`dt`) AS DATE) AS `dt`,   `mr_business_h5_regincome_d`.`income_huanbi` AS `income_huanbi`,   `mr_business_h5_regincome_d`.`income_mtd` AS `income_mtd`,   `mr_business_h5_regincome_d`.`income_pmtd` AS `income_pmtd`,   `mr_business_h5_regincome_d`.`income_uv_rate_mhuanbi` AS `income_uv_rate_mhuanbi`,   `mr_business_h5_regincome_d`.`income_uv_rate_mtd` AS `income_uv_rate_mtd`,   `mr_business_h5_regincome_d`.`income_uv_rate_pmtd` AS `income_uv_rate_pmtd`,   `mr_business_h5_regincome_d`.`product_id` AS `product_id`,   `mr_business_h5_regincome_d`.`product_name` AS `product_name`,   `mr_business_h5_regincome_d`.`register_cli_mhuanbi` AS `register_cli_mhuanbi`,   `mr_business_h5_regincome_d`.`register_cli_mtd` AS `register_cli_mtd`,   `mr_business_h5_regincome_d`.`register_cli_pmtd` AS `register_cli_pmtd`,   `mr_business_h5_regincome_d`.`register_mhuanbi` AS `register_mhuanbi`,   `mr_business_h5_regincome_d`.`register_mtd` AS `register_mtd`,   `mr_business_h5_regincome_d`.`register_pmtd` AS `register_pmtd`,   `mr_business_h5_regincome_d`.`unit_price` AS `unit_price` FROM `adm`.`mr_business_h5_regincome_d` `mr_business_h5_regincome_d`";
        List<String> l1 = new ParseTable2UDF().evaluate(a);
        System.out.println(l1);
    }
}